/**
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */

package org.geoscheduler.commons.marshaller.decls;

import org.geoscheduler.commons.marshaller.JSONFieldDecl;
import org.geoscheduler.commons.marshaller.JSONMarshaller;
import org.geoscheduler.commons.tools.PropertyDescriptor;
import org.geoscheduler.commons.tools.StringTools;

/**
 * 
 * <h2>JSONIntegerField</h2>
 * <p>
 * {@link Integer} property marshaller/unmarshaller
 * </p>
 * 
 * @author lko
 */
public class JSONIntegerField extends JSONAbstractSimpleFieldDecl<Integer> {

	public JSONIntegerField(PropertyDescriptor<Integer> desc, Integer defValue) {
		super(desc, defValue);
	}

	public JSONIntegerField(PropertyDescriptor<Integer> desc) {
		super(desc);
	}

	public Integer decString(String value) {
		return StringTools.isEmpty(value) ? getDefaultValue() : Integer.valueOf(value);
	}

	public String encString(Integer value) {
		return value == null ? null : value.toString();
	}

	@Override
	protected void setDefaultValue(Integer value) {
		if (value == null && int.class.isAssignableFrom(getType())) {
			super.setDefaultValue(Integer.valueOf(0));
		} else {
			super.setDefaultValue(value);
		}
	}

	public static class Factory extends BaseAbstractFactory<Integer> {

		public JSONFieldDecl<Integer> create(PropertyDescriptor<Integer> desc, JSONMarshaller marshaller) {
			return new JSONIntegerField(desc);
		}

		@Override
		public boolean isApplicable(PropertyDescriptor<?> desc) {
			return super.isApplicable(desc)
					&& (int.class.isAssignableFrom(desc.getType()) || Integer.class.isAssignableFrom(desc.getType()));
		}

	}

}